package com.party.mobile.web.controller.gatherForm;

import com.google.common.collect.Maps;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.gatherForm.GatherForm;
import com.party.core.model.gatherForm.GatherFormInfo;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.PartnerMember;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormOptionService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.notify.notifyPush.servce.INotifySendService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 表单
 */
@Controller
@RequestMapping("gatherForm/form")
public class GatherFormController {

    @Autowired
    private IGatherProjectService gatherProjectService;
    @Autowired
    private IGatherFormService gatherFormService;
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IGatherFormInfoService gatherFormInfoService;
    @Autowired
    private IGatherFormOptionService gatherFormOptionService;
    @Autowired
    private INotifySendService notifySendService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 表单项目详情
     *
     * @param projectId 项目id
     * @param isRender  true/false （true表示需要过滤html标签，false表示不用）
     * @return
     */
    @ResponseBody
    @RequestMapping("getDetails")
    public AjaxResult getDetails(String projectId, boolean isRender) {
        if (StringUtils.isEmpty(projectId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
        }
        GatherProject gatherProject = gatherProjectService.get(projectId);
        if (null == gatherProject || gatherProject.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "信息收集项目不存在");
        }
        if (StringUtils.isNotEmpty(gatherProject.getContent())) {
            String content = StringEscapeUtils.unescapeHtml4(gatherProject.getContent());
            if (isRender) {
                content = StringUtils.removeHtmlTag(content);
            }
            gatherProject.setContent(content);
        }

        List<GatherForm> gatherForms = gatherProjectBizService.getFormItems(projectId, true);
        gatherProject.setItems(gatherForms);
        return AjaxResult.success(gatherProject);
    }

    @ResponseBody
    @RequestMapping("save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(GatherProject project, BindingResult result, HttpServletRequest request) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        if (StringUtils.isEmpty(project.getId())) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
        }

        try {
            GatherProject gatherProject = gatherProjectService.get(project.getId());
            if (null == gatherProject) {
                return AjaxResult.error(PartyCode.IS_NO_DATA, "项目不存在");
            }

            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
            String currentId = null;
            if (null != currentUser) {
                currentId = currentUser.getId();
            }
            GatherProject dbProject = gatherProjectBizService.saveFormInfoBiz(project.getInfoItems(), project.getId(), currentId, null);

            if (StringUtils.isNotEmpty(dbProject.getIsRemindMe()) && Integer.valueOf(dbProject.getIsRemindMe()).equals(YesNoStatus.YES.getCode())) {
                if (StringUtils.isNotEmpty(dbProject.getPhone())) {
                    notifySendService.sendSuccessForm(dbProject.getPhone(), dbProject);
                } else {
                    MemberGroup member = memberGroupService.get(dbProject.getCreateBy());
                    notifySendService.sendSuccessForm(member.getMobile(), dbProject);
                }
            }
            if (StringUtils.isNotEmpty(currentId)) {
                // 机构成员所属
                PartnerMember partnerMember = new PartnerMember();
                String partnerId = gatherProjectService.get(project.getId()).getCreateBy();

                partnerMember.setPartnerId(partnerId);
                partnerMember.setMemberId(currentId);
                partnerMemberService.getSet(partnerMember);

                // 个人统计表添加数据
                memberPersonalCountBizService.getSet(partnerId, currentId);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("信息保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(100, "信息保存失败");
        }
    }

    /**
     * 根据业务id获取填写数据
     *
     * @param projectId 项目id
     * @param targetId  业务id
     * @return
     */
    @ResponseBody
    @RequestMapping("getFormInfoByTargetId")
    public AjaxResult getFormInfoByTargetId(String projectId, String targetId, boolean isNew) {
        if (StringUtils.isEmpty(projectId) || StringUtils.isEmpty(targetId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "id不能为空");
        }
        try {
            Map<String, Object> result = Maps.newHashMap();
            if (isNew) {
                List<GatherForm> fields = gatherFormService.list(new GatherForm(projectId));
                result.put("fields", fields);
            }

            GatherFormInfo t = new GatherFormInfo();
            t.setProjectId(projectId);
            t.setTargetId(targetId);
            List<GatherFormInfo> infos = gatherFormInfoService.list(t);
            result.put("infos", infos);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("");
            logger.error("获取业务id对应的数据异常", e);
            return AjaxResult.error(100, "获取数据异常");
        }
    }
}
